! This file is part of PanGu. All rights reserved.
module pangu_write

    use seakeeping_kinds, only: rk
    use seakeeping_error, only: file_write_error
    use seakeeping_constants, only: fmt

contains

    !> 写入载荷文件
    subroutine write_load_file(load_file, load, nstation, error)
        character(*), intent(in) :: load_file  !! 载荷文件名
        real(rk), dimension(2, 0:nstation), intent(in) :: load  !! 载荷
        integer, intent(in) :: nstation  !! 站点数
        character(:), allocatable, intent(out) :: error  !! 错误信息
        integer :: fid, i, istat

        open (newunit=fid, file=load_file, status='replace', &
              action='write', iostat=istat)
        if (istat /= 0) then
            call file_write_error(error, load_file, 'file cannot be written, may be occupied by other programs')
            return
        end if

        write (fid, '(a)', iostat=istat) 'No.station, shear force(N), bending moment(N*m)'
        if (istat /= 0) then
            call file_write_error(error, load_file, 'file cannot be written, may be occupied by other programs')
            close (fid)
            return
        end if

        do i = 0, nstation
            write (fid, fmt(2)) i, load(1, i), load(2, i)
        end do
        close (fid)

    end subroutine write_load_file

    !> 写入加速度文件
    subroutine write_acc_file(acc_file, acc, nstation, error)
        character(*), intent(in) :: acc_file  !! 加速度文件名
        real(rk), dimension(nstation), intent(in) :: acc  !! 加速度
        integer, intent(in) :: nstation  !! 站点数
        character(:), allocatable, intent(out) :: error  !! 错误信息
        integer :: fid, i, istat

        open (newunit=fid, file=acc_file, status='replace', &
              action='write', iostat=istat)
        if (istat /= 0) then
            call file_write_error(error, acc_file, 'file cannot be written, may be occupied by other programs')
            return
        end if

        write (fid, '(a)', iostat=istat) 'No.mass, acceleration(m/s^2)'
        if (istat /= 0) then
            call file_write_error(error, acc_file, 'file cannot be written, may be occupied by other programs')
            close (fid)
            return
        end if

        do i = 1, nstation
            write (fid, fmt(2)) i, acc(i)
        end do
        close (fid)

    end subroutine write_acc_file

end module pangu_write
